﻿#region File Description
/*-----------------------------------------------------------------------------
 Author: Jose Antonio Gallego
 Date: 24/10/2011
 
 License: Ms-PL
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.

 The example companies, organizations, products, domain names,
 e-mail addresses, logos, people, places, and events depicted
 herein are fictitious.  No association with any real company,
 organization, product, domain name, email address, logo, person,
 places, or events is intended or should be inferred.
-----------------------------------------------------------------------------*/
#endregion

using System;
using System.Windows;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

namespace Zombsquare.Pages.Bestiario
{
    public partial class BestiarioPage : PhoneApplicationPage
    {
        ContentManager contentManager;
        GameTimer timer;
        SpriteBatch spriteBatch;

        UIElementRenderer elementRender;

        // Campos para el modelo
        Model model;        
        Vector3 modelPosition;
        float modelRotation;

        // Matrices para el control de la camara                
        Matrix cameraViewMatrix;
        Matrix cameraProjectionMatrix;
        
        public BestiarioPage()
        {
            InitializeComponent();

            // Get the content manager from the application
            contentManager = (Application.Current as App).Content;

            // Create a timer for this page
            timer = new GameTimer();
            timer.UpdateInterval = TimeSpan.FromTicks(333333);
            timer.Update += OnUpdate;
            timer.Draw += OnDraw;
        }


        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // Set the sharing mode of the graphics device to turn on XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(true);

            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(SharedGraphicsDeviceManager.Current.GraphicsDevice);

            // TODO: use this.content to load your game content here

            // Cargar el modelo
            model = contentManager.Load<Model>("zombinejo/zombinejo");
            modelPosition = Vector3.Zero;
            modelRotation = 0f;

            // Inicializar la Camara
            cameraViewMatrix = Matrix.CreateLookAt(new Vector3(0,5,50), modelPosition, Vector3.Up);
            cameraProjectionMatrix = Matrix.CreatePerspectiveFieldOfView(0.45f,
                                                                          SharedGraphicsDeviceManager.Current.GraphicsDevice.DisplayMode.AspectRatio,                                                                            
                                                                          1f, 500f);

            // Start the timer
            timer.Start();

            base.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            // Stop the timer
            timer.Stop();

            // Set the sharing mode of the graphics device to turn off XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(false);

            base.OnNavigatedFrom(e);
        }

        /// <summary>
        /// Allows the page to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        private void OnUpdate(object sender, GameTimerEventArgs e)
        {
            // TODO: Add your update logic here

            //Actualizamos la rotación
            modelRotation = (float)e.TotalTime.TotalSeconds * 0.6f;
        }

        /// <summary>
        /// Allows the page to draw itself.
        /// </summary>
        private void OnDraw(object sender, GameTimerEventArgs e)
        {
            SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(new Color(137, 19, 19));



            SharedGraphicsDeviceManager.Current.GraphicsDevice.DepthStencilState = DepthStencilState.Default;
            SharedGraphicsDeviceManager.Current.GraphicsDevice.BlendState = BlendState.Opaque;

            // TODO: Add your drawing code here
            foreach (ModelMesh mesh in model.Meshes)
            {
                foreach (BasicEffect effect in mesh.Effects)
                {
                    effect.EnableDefaultLighting();
                    effect.SpecularColor = Color.White.ToVector3();

                    effect.LightingEnabled = true;
                    effect.DirectionalLight0.Direction = Vector3.Forward;
                    effect.DirectionalLight0.Enabled = true;
                    effect.DirectionalLight0.SpecularColor = Color.White.ToVector3();               

                    effect.World = Matrix.CreateRotationY(modelRotation) * Matrix.CreateTranslation(modelPosition);
                    effect.View = cameraViewMatrix;
                    effect.Projection = cameraProjectionMatrix;
                }
                mesh.Draw();
            }

            elementRender.Render();

            spriteBatch.Begin();
            spriteBatch.Draw(elementRender.Texture, Vector2.Zero, Color.White);
            spriteBatch.End();        
        
        }

        private void PhoneApplicationPage_LayoutUpdated(object sender, EventArgs e)
        {
            if ((ActualWidth > 0) && (ActualHeight > 0))
            {
                SharedGraphicsDeviceManager.Current.PreferredBackBufferWidth = 480;
                SharedGraphicsDeviceManager.Current.PreferredBackBufferHeight = 800;
            }

            if (elementRender == null)
            {
                elementRender = new UIElementRenderer(this, 480, 800);
            }
        }
    }
}